package com.qsboss.demo.controller;

import com.qsboss.demo.domain.Result;
import com.qsboss.demo.service.TbBillService;
import lombok.extern.slf4j.Slf4j;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.UUID;

/**
 * @author 军哥
 * @version 1.0
 * @description: TODO
 * @date 2023/10/23 21:40
 */
@Controller
@Slf4j
@RequestMapping(value = "/act")
public class ActivitiController {

    @Autowired
    RepositoryService repositoryService;

    @Autowired
    RuntimeService runtimeService;

    @Autowired
    TaskService taskService;

    @Autowired
    TbBillService tbBillService;

    /***
     * @description 部署流程
     * @params bpmnXml
     * @return com.qsboss.demo.domain.Result
     * @author 军哥
     * @date 2023/10/23 22:03
     */

    @PostMapping(value = "/deploy")
    @ResponseBody
    public Result deploy(String bpmnXml, String bpmnPng) {
        Deployment deploy = repositoryService.createDeployment()
                .addClasspathResource("activiti/" + bpmnXml)
                .addClasspathResource("activiti/" + bpmnPng)
                .deploy();
        if(deploy != null) {
            log.info("deploy:" + deploy.getId());
            return Result.SUCCESS();
        }

        return Result.FAILED(500, "部署发生未知错误");
    }

    /***
     * @description 申请启动一个流程实例
     * @params key
     * @return com.qsboss.demo.domain.Result
     * @author 军哥
     * @date 2023/10/23 22:47
     */
    @PostMapping(value = "/start")
    @ResponseBody
    public Result start(String key) {
        String businessKey = UUID.randomUUID().toString();

        //-- 获取流程信息
        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().processDefinitionKey(key).singleResult();
        System.out.println(processDefinition.getKey());
        System.out.println(processDefinition.getName());

        HashMap<String, Object> map = new HashMap<>();

        if(key.equals("closebill")) {
            // 结账流程
            map.put("user1", "李主管");
            map.put("user2", "王经理");
        }
        else if(key.equals("evection")) {
            // 出差流程
            map.put("user1", "李科长");
            map.put("user2", "王处长");
        }

        ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(key, businessKey, map);
        if(processInstance != null) {
            log.info("processId:" + processInstance.getId());
            return Result.SUCCESS();
        }

        return Result.FAILED(500, "申请流程发生未知错误");
    }

    /***
     * @description 审批流程
     * @params pid 流程ID
     * @params taskId 任务ID
     * @params optCode 审批操作码： 1通过2驳回3终止
     * @return com.qsboss.demo.domain.Result
     * @author 军哥
     * @date 2023/10/23 22:52
     */
    @PostMapping(value = "/task")
    @ResponseBody
    public Result task(String pid, String taskId, Integer optCode) {
        //--1 查询实例流程
        ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceId(pid).singleResult();
        if(processInstance == null) {
            return Result.FAILED(404, "流程实例不存在");
        }

//        Task task = taskService.createTaskQuery().taskId(taskId).singleResult();
//        if(task == null) {
//            return Result.FAILED(404, "审批任务不存在");
//        }

        String businessKey = processInstance.getBusinessKey();
        HashMap<String, Object> map = new HashMap<>();
        map.put("optCode", optCode);

        //--2 完成下一步的流程
        taskService.complete(taskId, map);

        //-- 查询流程是否为最后一步审批
        ProcessInstance lastProcess = runtimeService.createProcessInstanceQuery().processInstanceId(pid).singleResult();
        if(lastProcess == null) {
            // 发送通知邮件或者短信
            System.out.println("发送邮件通知用户");
            System.out.println("修改审核状态：审核结束");

            // 设置业务数据的销账状态
            if(optCode == 1) {
                // 通过则销账
                tbBillService.setBillPayAck(Integer.valueOf(businessKey), 2);
            }
            else {
                // 不通过则取消还款状态
                tbBillService.setBillPayAck(Integer.valueOf(businessKey), 0);
            }
        }

        return Result.SUCCESS();
    }


}
